<?php

namespace common\repositories\myhtsq;

use Yii;
use common\error\ErrorCode;

use common\entities\myhtsq\RoleUserEntity;
use common\repositories\BaseRepository;
use common\entities\myhtsq\RoleEntity;

class RoleUserRepository extends BaseRepository {

    /**
     * 构造方法
     * @param unknown $config (optional)
     */
    public function __construct($config = []) {
        parent::__construct($config);
    }

    /**
     * 获取用户所属角色列表
     * @param string $userId 用户ID
     * @return array|ActiveRecord[] 用户角色列表
     */
    public static function getRolesByUserId($userId) {
        return RoleUserEntity::find()->where(['user_id' => $userId])->all();
    }

    /**
     * 检查是否唯一的角色
     * @param int $roleId 角色id
     * @return array
     */
    public static function getRoleUserList($roleId) {
        return RoleUserEntity::find()->where(['role_id' => $roleId])->all();
    }
    
    /**
     * 根据角色id,获取列表
     * @param int $user_id 用户ID
     * @return array
     */
    public static function getRoleIdsByUserId($user_id) {
        return RoleUserEntity::find()->select('role_id')->where(['user_id' => $user_id])->distinct()->column();
    }

    /**
     * 获取用户角色信息
     * @param $userId
     * @return array
     */
    public function getRoleNameList($userId)
    {
        $roleIdList = $this->getRoleIdsByUserId($userId);
        $roleList = RoleEntity::find()
            ->select('role_id,role_name')
            ->where(['in', 'role_id', $roleIdList])
            ->asArray()
            ->all();
        return ['roleIdList' => $roleIdList, 'roleList' => $roleList];
    }

    /**
     * 设置和取消区域负责角色
     * @param $userGUID
     */
    public function setAreaCharge($userGUID)
    {
        $areaChargeEntity = RoleUserEntity::find()
            ->where(['user_id'=>$userGUID, 'role_id' => 15])
            ->one();
        if (empty($areaChargeEntity)){
            $roleUserEntity = new RoleUserEntity();
            $roleUserEntity->role_id = 15;
            $roleUserEntity->user_id = $userGUID;
            $roleUserEntity->created_by = Yii::$app->user->identity->username;
            $roleUserEntity->modified_by = Yii::$app->user->identity->username;
            return $roleUserEntity->save();
        }
        return $areaChargeEntity->delete();
    }

    /**
     * 判断是否为区域负责人
     * @param $userGUID
     * @return int|string
     */
    public function checkIsAreaAuthRole($userGUID)
    {
        return RoleUserEntity::find()
            ->where(['user_id' => $userGUID, 'role_id' => 15])
            ->count();
    }



}
